package tcc.wa.presenter;

import java.util.List;

import tcc.wa.R;
import tcc.wa.model.Alert;
import tcc.wa.presenter.view.AlertView;
import tcc.wa.service.AlertService;
import tcc.wa.service.factory.ServiceFactory;
import android.util.Log;

/**
 * Presenter class for Alerts
 */
public class AlertPresenter {
	
	private final String TAG = "AlertPresenter";
	
	private final AlertView view;
	
	private final AlertService alertService;
	
	public AlertPresenter(AlertView view) {
		this.view = view;
		alertService = ServiceFactory.getAlertService(view.getContext());
	}
	
	/**
	 * Called when view gets created.
	 */
	public void onCreate() {
		this.view.initView(R.layout.alert);
	}
	
	/**
	 * Update alerts.
	 */
	public void updateAlerts() {
		try {
			List<Alert> alerts = alertService.findAll();
			if (alerts != null)
				view.setAlertList(alerts);
		} catch (Exception e) {
			Log.e(TAG, "Error while obtaining alerts: " + e.getMessage() + "\n" + e.toString());
		}
	}
	
	/**
	 * New alert.
	 */
	public void newAlert() {
		view.displayAlertEnrollment();
	}
	
	/**
	 * Deletes an alert.
	 *
	 * @param alertId the alert id
	 */
	public void deleteAlert(long alertId) {
		try {
			alertService.delete(alertId);
			updateAlerts();
		} catch (Exception e) {
			Log.e(TAG, String.format("Error while deleting alert: %s\n%s", e.getMessage(), e.toString()));
			view.showToast("Erro ao remover alerta");
		}
	}
}